package com.ruoyi.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.product.vo.TbProduct;
import com.ruoyi.product.service.TbProductService;
import com.ruoyi.product.mapper.TbProductMapper;
import com.ruoyi.system.api.model.PageInfoVo;
import com.ruoyi.system.api.model.ProductInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class TbProductServiceImpl extends ServiceImpl<TbProductMapper, TbProduct>
    implements TbProductService{

    @Autowired
    TbProductMapper tbProductMapper;


    @Override
    public AjaxResult list(PageInfoVo pageInfoVo) {
        Page<TbProduct> page = new Page(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        Page<TbProduct> tbHirePage = tbProductMapper.selectPage(page, new QueryWrapper<>());

        List<ProductInfoVo> hireInfoVos = tbHirePage.getRecords().stream().map(item -> {
            ProductInfoVo hireInfoVo = new ProductInfoVo();
            BeanUtils.copyProperties(item, hireInfoVo);
            return hireInfoVo;
        }).collect(Collectors.toList());
        Page<ProductInfoVo> page1 = new Page<>();
        page1.setRecords(hireInfoVos);
        page1.setTotal(tbHirePage.getTotal());
        page1.setCurrent(tbHirePage.getCurrent());
        page1.setSize(tbHirePage.getSize());
        return AjaxResult.success(page1);
    }

    @Override
    public AjaxResult add(TbProduct tbProduct) {
        int insert = tbProductMapper.insert(tbProduct);
        if(insert>0){
            return AjaxResult.success("添加成功");
        }else {
            return AjaxResult.error("添加失败");
        }
    }

    @Override
    public AjaxResult updateById(ProductInfoVo productInfoVo) {
        Integer hireId = productInfoVo.getProductId();
        QueryWrapper<TbProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbProduct::getProductId,hireId);
        TbProduct tbHire = tbProductMapper.selectOne(queryWrapper);
        if(tbHire==null){
            return AjaxResult.error("该渠道不存在");
        }
        TbProduct pageInfoVo = new TbProduct();
        BeanUtils.copyProperties(productInfoVo,pageInfoVo);
        tbProductMapper.updateById(pageInfoVo);
        return AjaxResult.success("修改成功");
    }

    @Override
    public AjaxResult deleteById(Integer id) {


        int i = tbProductMapper.deleteById(id);
        if(i>0){
            return AjaxResult.success("删除成功");
        }else {
            return AjaxResult.error("删除失败");
        }

    }


}




